<?php
/**
 * Created by PhpStorm.
 * User: chenzhitao
 * Date: 2018/6/20
 * Time: 下午7:19
 */

namespace app\index\service;


use app\index\model\Level;
use app\index\model\Quota;
use app\index\model\SubCategory;
use app\index\model\SupCategory;

class CategoryService
{
    const CATEGORY_KEY = "category_list_key";
    const CATEGORY_ID_KEY = "category_id_key";
    const ALL_SUB_CATEGORY_LIST_KEY = "all_sub_category_list_key";
    const EXPIRE_IN = 60*60*12;
    public static function getSupCategoryList(){
        $category_list = cache(self::CATEGORY_KEY);
        if($category_list){
            return $category_list;
        }
        $data = SupCategory::getAll();
        foreach ($data as &$item){
            $subcategorys = SubCategory::getSubCategoryByPid($item["id"]);
            foreach ($subcategorys as &$subcategory){
                $subcategory["levels"] = Quota::getLevelsByCateId($subcategory["id"]);
            }
            $item['subcategoy'] = $subcategorys;

        }
        cache(self::CATEGORY_KEY, $data, self::EXPIRE_IN);
        return $data;
    }
    public static function getCategoryNamesBySubCateId($subcategory_id){
        $subcategory = SubCategory::getCategoryById($subcategory_id);
        if($subcategory == null){
            return "";
        }
        $subcatename = $subcategory['category_name'];

        $supcate = SupCategory::getCategoryById($subcategory['parent_cate_id']);
        $supcatename = "";
        if($supcate){
            $supcatename = $supcate["category_name"];
        }

        return $supcatename."-".$subcatename;
    }
    public static function getSupCategoryById($id){
        $category = cache(self::CATEGORY_ID_KEY.$id);
        if($category){
            return $category;
        }
        $data = SupCategory::getCategoryById($id);
        $data['subcategorys'] = SubCategory::getLimitSubCategoryByPid($data["id"]);
        cache(self::CATEGORY_ID_KEY.$id, $data, self::EXPIRE_IN);
        return $data;

    }
    public static function getAllSubCategoryList(){
       $cache_sub_category_list = cache(self::ALL_SUB_CATEGORY_LIST_KEY);
        if($cache_sub_category_list){
            return $cache_sub_category_list;
        }
        $data = SubCategory::getAll();
        cache(self::ALL_SUB_CATEGORY_LIST_KEY, $data, self::EXPIRE_IN);
        return $data;
    }
    public static function getCategoryAndLevelNamesBySubCateId($subcategory_id,$level){

        $subcategory = SubCategory::getCategoryById($subcategory_id);
        if($subcategory == null){
            return "";
        }
        $subcatename = $subcategory['category_name'];

        $supcate = SupCategory::getCategoryById($subcategory['parent_cate_id']);
        $supcatename = "";
        if($supcate){
            $supcatename = $supcate["category_name"];
        }
        $level_name = Level::getLevelNameById($level);
        return $supcatename."-".$subcatename."-".$level_name;
    }


}